import React, { useEffect, useRef, useState } from "react";
import styles from "./PostEditPage.module.css";
import {
    Button,
    Form,
    FormInstance,
    Input,
    InputNumber,
    Typography,
} from "antd";
import moment from "moment";
import { History, Location } from "history";
import SelectUser from "./component/SelectUser";
import { useDispatch } from "react-redux";
import { postEdit } from "./slice/postSlice";

interface Props {
    history: History;
    location: Location;
}

/**
 * 帖子列表
 * */
const PostEditPage = ({ history, location }: Props) => {
    const dispatch = useDispatch();

    const [loading, setLoading] = useState(false);
    const formRef = useRef<FormInstance>(null);

    const onFinish = (data: any) => {
        setLoading(true);
        setTimeout(() => {
            setLoading(false);
            const date = moment().format("YYYY-MM-DD HH:MM:SS");
            dispatch(postEdit({ ...data, date }));
            history.goBack();
        }, 1500);
    };

    useEffect(() => {
        const { state } = location;
        if (state) {
            formRef.current?.setFieldsValue(state);
        }
    }, [location]);

    return (
        <div className={styles.main}>
            <Typography.Title level={3}>编辑帖子</Typography.Title>
            <Form layout={"vertical"} onFinish={onFinish} ref={formRef}>
                <Form.Item label="ID" name={"id"} rules={[{ required: true }]}>
                    <InputNumber style={{ width: "100%" }} />
                </Form.Item>
                <Form.Item
                    label="标题"
                    name={"title"}
                    rules={[{ required: true }]}
                >
                    <Input style={{ width: "100%" }} />
                </Form.Item>
                <Form.Item
                    label="作者"
                    name={"author"}
                    rules={[{ required: true }]}
                >
                    <SelectUser />
                </Form.Item>
                <Form.Item
                    label="内容"
                    name={"content"}
                    rules={[{ required: true }]}
                >
                    <Input.TextArea style={{ width: "100%" }} />
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit" loading={loading}>
                        保存
                    </Button>
                </Form.Item>
            </Form>
        </div>
    );
};
export default PostEditPage;
